package com.asiainfo.gateway.predicate;

import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class DIYRoutePredicateFactory extends AbstractRoutePredicateFactory<DIYRoutePredicateFactory.Config>{


    //无参构造
    public DIYRoutePredicateFactory() {
        super(DIYRoutePredicateFactory.Config.class);
    }

    //参数顺序
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name","value");
    }

    //断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(DIYRoutePredicateFactory.Config config) {

        return new GatewayPredicate() {
            /**
             * 测试方法，用于判断给定的服务器Web交换是否满足某些条件
             *
             * @param serverWebExchange 服务器Web交换对象，包含请求和响应信息
             * @return boolean 测试结果，true表示满足条件，false表示不满足条件
             */
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //从serverWebExchange中获取请求参数
                String name = serverWebExchange.getRequest().getQueryParams().getFirst(config.getName());
                if (name != null && name.equals(config.getValue())) {
                    return true;
                }
                return false;
            }
        };
    }


    public static class Config {

        public Config() {
        }
        @NotEmpty
        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }


}
